package com.xsz.service;

import java.util.List;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;


import com.xsz.entity.User;
import com.xsz.repository.UserRepository;
import com.xsz.util.KeyUtil;

@Service
public class UserService {
	@Resource
	UserRepository userRepository;
	@Resource 
	RedisTemplateService redisTemplateService;
	
	public User add(User user) {
		user.setId(KeyUtil.getId());
		return userRepository.save(user);
	}
	
	
	public User getById(String id) {
		User user = redisTemplateService.get(id+"login",User.class);
		if(user==null) {
			user=userRepository.findById(id).get();
			redisTemplateService.set(user.getId()+"login",user);
		}
		return user;
	}
	
	
	public int update(String id,String mobile) {
		int rsint=userRepository.updateMobileById(mobile,id);
		if(rsint>0) {
			User user = redisTemplateService.get(id+"login",User.class);
			user.setMobile(mobile);
			redisTemplateService.set(user.getId()+"login",user);
		}
		
		return rsint;
	}
	
	public List<User> getAll() {
		return userRepository.findAll();
	}
	
	public User login(String name,String pwd) {
		User user=userRepository.findByNameAndPwd(name, pwd);
		redisTemplateService.set(user.getId()+"login",user);
		
		return user;
	}
	
	public List<User> likeName(String name) {
		return userRepository.findByNameLike(name+"%");
	}

}
